package com.example.demo.config;


import com.example.demo.util.RedisUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.annotation.PostConstruct;
import jakarta.annotation.Resource;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.connection.stream.MapRecord;
import org.springframework.data.redis.connection.stream.RecordId;
import org.springframework.data.redis.stream.StreamListener;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * @author ：zz
 * @date ：Created in 2022/5/19 10:15
 * @description：消费监听
 */
@Slf4j
@Component
public class ConsumeListenerFjitter implements StreamListener<String, MapRecord<String, String, String>> {

    @Resource
    private RedisUtil redisUtil;


    private static ConsumeListenerFjitter consumeListenerFjitter;

    @PostConstruct
    public void init(){
        consumeListenerFjitter = this;
        consumeListenerFjitter.redisUtil=this.redisUtil;

    }


    @SneakyThrows
    public void onMessage(MapRecord<String, String, String> message) {
        ObjectMapper objectMapper = new ObjectMapper();
        String stream = message.getStream();
		RecordId id = message.getId();
		Map<String, String> map = message.getValue();
		log.info("[手动ack] group:[group-fjitter] consumerName:[{}] 接收到一个消息 stream:[{}],value:[{}]", stream, id, map);
        consumeListenerFjitter.redisUtil.ack(stream, "group-fjitter", id.getValue());
        consumeListenerFjitter.redisUtil.del(stream, id.getValue());
		log.info(objectMapper.writeValueAsString(map));
    }


}
